import { sendSms } from "@/service";
import { findComponentUpward } from "@libs/assist";
let timer = null;
export default {
  props: {
    mobile: [Number, String],
    value: [Number, String],
    validFn: Function, //函数？为什么酱紫写？有啥好处？
  },
  data() {
    return {
      loading: false,
      second: 119,
    };
  },
  computed: {
    msg() {
      return this.loading ? `${this.second}秒后重发` : "发送验证码";
    },
    code: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit("input", val);
      },
    },
  },
  methods: {
    validatePhone() {
      //传递函数
      this.validFn().then((valid) => {
        if (valid) {
          this.code = "";
          this.sendSms();
        }
      });
    },
    async sendSms() {
      if (this.loading) return; //防止多次调用接口
      this.load();
      const [err, data] = await sendSms({
        mobile: this.mobile,
        ltId: findComponentUpward(this, "Home").securityConfig._lt,
      });
      if (err) {
        this.errors(err);
        return;
      }
      this.success("验证码已发送，请注意查收");
      this.createInterval();
    },
    createInterval() {
      this.loading = true;
      clearInterval(timer);
      timer = setInterval(() => {
        this.second--;
        if (this.second === 0) {
          clearInterval(timer);
          this.second = 119;
          this.loading = false;
        }
      }, 1000);
      //清除定时器比较好的方案是使用$once来清除定时器, hook:beforeDestroy:当前组件的生命周期函数
      this.$once("hook:beforeDestroy", function() {
        clearInterval(timer);
      });
    },
  },
};
